{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0d2713ef",
   "metadata": {},
   "source": [
    "# Tutorial 06, case 7b: Stokes problem with Neumann control\n",
    "\n",
    "In this tutorial we solve the optimal control problem\n",
    "\n",
    "$$\\min J(y, u) = \\frac{1}{2} \\int_{\\Gamma_{obs}} (v - v_d)^2 dx + \\frac{\\alpha_1}{2} \\int_{\\Gamma_C} |\\nabla_{\\mathbf{t}} u|^2 ds + \\frac{\\alpha_2}{2} \\int_{\\Gamma_C} |u|^2 ds$$\n",
    "s.t.\n",
    "$$\\begin{cases}\n",
    "- \\nu \\Delta v + \\nabla p = f       & \\text{in } \\Omega\\\\\n",
    "             \\text{div} v = 0       & \\text{in } \\Omega\\\\\n",
    "                        v = g       & \\text{on } \\Gamma_{in}\\\\\n",
    "                        v = 0       & \\text{on } \\Gamma_{w}\\\\\n",
    "   p n - \\nu \\partial_n v = u       & \\text{on } \\Gamma_{C}\n",
    "\\end{cases}$$\n",
    "\n",
    "where\n",
    "$$\\begin{align*}\n",
    "& \\Omega                      & \\text{unit square}\\\\\n",
    "& \\Gamma_{in}                 & \\text{has boundary id 1}\\\\\n",
    "& \\Gamma_{w}                  & \\text{has boundary id 2}\\\\\n",
    "& \\Gamma_{C}                  & \\text{has boundary id 3}\\\\\n",
    "& \\Gamma_{obs}                & \\text{has interface id 4}\\\\\n",
    "& u \\in [L^2(\\Gamma_C)]^2     & \\text{control variable}\\\\\n",
    "& v \\in [H^1(\\Omega)]^2       & \\text{state velocity variable}\\\\\n",
    "& p \\in L^2(\\Omega)           & \\text{state pressure variable}\\\\\n",
    "& \\alpha_1, \\alpha_2 > 0      & \\text{penalization parameters}\\\\\n",
    "& v_d                         & \\text{desired state}\\\\\n",
    "& f                           & \\text{forcing term}\\\\\n",
    "& g                           & \\text{inlet profile}\\\\\n",
    "\\end{align*}$$\n",
    "using an adjoint formulation solved by a one shot approach.\n",
    "\n",
    "The test case is from section 5.5 of\n",
    "F. Negri. Reduced basis method for parametrized optimal control problems governed by PDEs. Master thesis, Politecnico di Milano, 2010-2011."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f30a8630",
   "metadata": {},
   "outputs": [],
   "source": [
    "import dolfinx.fem\n",
    "import dolfinx.io\n",
    "import dolfinx.mesh\n",
    "import gmsh\n",
    "import mpi4py.MPI\n",
    "import numpy as np\n",
    "import numpy.typing\n",
    "import petsc4py.PETSc\n",
    "import ufl\n",
    "import viskex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "658c4aa0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import multiphenicsx.fem\n",
    "import multiphenicsx.fem.petsc"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dac2931",
   "metadata": {},
   "source": [
    "### Geometrical parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9005416",
   "metadata": {},
   "outputs": [],
   "source": [
    "mu1 = 1.0\n",
    "mu2 = np.pi / 5.0\n",
    "mu3 = np.pi / 6.0\n",
    "mu4 = 1.0\n",
    "mu5 = 1.7\n",
    "mu6 = 2.2\n",
    "mesh_size = 0.05"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49905e02",
   "metadata": {},
   "source": [
    "### Mesh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2a1ce9f",
   "metadata": {},
   "outputs": [],
   "source": [
    "Y = 1.0\n",
    "X = -Y\n",
    "L = 3.0\n",
    "B = Y - mu1\n",
    "H_1 = B + np.tan(mu2) * mu5\n",
    "H_2 = B - np.tan(mu3) * mu6\n",
    "L_1 = mu1 * np.cos(mu2) * np.sin(mu2)\n",
    "L_2 = (B - X) * np.cos(mu3) * np.sin(mu3)\n",
    "N = mu1 * np.cos(mu2) * np.cos(mu2)\n",
    "M = - (B - X) * np.cos(mu3) * np.cos(mu3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8650290",
   "metadata": {},
   "outputs": [],
   "source": [
    "gmsh.initialize()\n",
    "gmsh.model.add(\"mesh\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a74fdb5",
   "metadata": {},
   "outputs": [],
   "source": [
    "p0 = gmsh.model.geo.addPoint(0.0, X, 0.0, mesh_size)\n",
    "p1 = gmsh.model.geo.addPoint(L - mu4, X, 0.0, mesh_size)\n",
    "p2 = gmsh.model.geo.addPoint(L, X, 0.0, mesh_size)\n",
    "p3 = gmsh.model.geo.addPoint(L + mu6 - L_2, H_2 + M, 0.0, mesh_size)\n",
    "p4 = gmsh.model.geo.addPoint(L + mu6, H_2, 0.0, mesh_size)\n",
    "p5 = gmsh.model.geo.addPoint(L, B, 0.0, mesh_size)\n",
    "p6 = gmsh.model.geo.addPoint(L + mu5, H_1, 0.0, mesh_size)\n",
    "p7 = gmsh.model.geo.addPoint(L + mu5 - L_1, H_1 + N, 0.0, mesh_size)\n",
    "p8 = gmsh.model.geo.addPoint(L, Y, 0.0, mesh_size)\n",
    "p9 = gmsh.model.geo.addPoint(L - mu4, Y, 0.0, mesh_size)\n",
    "p10 = gmsh.model.geo.addPoint(0.0, Y, 0.0, mesh_size)\n",
    "l0 = gmsh.model.geo.addLine(p0, p1)\n",
    "l1 = gmsh.model.geo.addLine(p1, p2)\n",
    "l2 = gmsh.model.geo.addLine(p2, p3)\n",
    "l3 = gmsh.model.geo.addLine(p3, p4)\n",
    "l4 = gmsh.model.geo.addLine(p4, p5)\n",
    "l5 = gmsh.model.geo.addLine(p5, p6)\n",
    "l6 = gmsh.model.geo.addLine(p6, p7)\n",
    "l7 = gmsh.model.geo.addLine(p7, p8)\n",
    "l8 = gmsh.model.geo.addLine(p8, p9)\n",
    "l9 = gmsh.model.geo.addLine(p9, p10)\n",
    "l10 = gmsh.model.geo.addLine(p10, p0)\n",
    "l11 = gmsh.model.geo.addLine(p1, p9)\n",
    "l12 = gmsh.model.geo.addLine(p2, p5)\n",
    "l13 = gmsh.model.geo.addLine(p5, p8)\n",
    "line_loop_rectangle_left = gmsh.model.geo.addCurveLoop([l0, l11, l9, l10])\n",
    "line_loop_rectangle_right = gmsh.model.geo.addCurveLoop([l1, l12, l13, l8, -l11])\n",
    "line_loop_bifurcation_top = gmsh.model.geo.addCurveLoop([l5, l6, l7, -l13])\n",
    "line_loop_bifurcation_bottom = gmsh.model.geo.addCurveLoop([l2, l3, l4, -l12])\n",
    "rectangle_left = gmsh.model.geo.addPlaneSurface([line_loop_rectangle_left])\n",
    "rectangle_right = gmsh.model.geo.addPlaneSurface([line_loop_rectangle_right])\n",
    "bifurcation_top = gmsh.model.geo.addPlaneSurface([line_loop_bifurcation_top])\n",
    "bifurcation_bottom = gmsh.model.geo.addPlaneSurface([line_loop_bifurcation_bottom])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff5e656c",
   "metadata": {},
   "outputs": [],
   "source": [
    "gmsh.model.geo.synchronize()\n",
    "gmsh.model.addPhysicalGroup(1, [l10], 1)\n",
    "gmsh.model.addPhysicalGroup(1, [l0, l1, l2, l4, l5, l7, l8, l9], 2)\n",
    "gmsh.model.addPhysicalGroup(1, [l3, l6], 3)\n",
    "gmsh.model.addPhysicalGroup(1, [l11], 4)\n",
    "gmsh.model.addPhysicalGroup(2, [rectangle_left], 1)\n",
    "gmsh.model.addPhysicalGroup(2, [rectangle_right], 2)\n",
    "gmsh.model.addPhysicalGroup(2, [bifurcation_top], 3)\n",
    "gmsh.model.addPhysicalGroup(2, [bifurcation_bottom], 4)\n",
    "gmsh.model.mesh.generate(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9355c95",
   "metadata": {},
   "outputs": [],
   "source": [
    "partitioner = dolfinx.mesh.create_cell_partitioner(dolfinx.mesh.GhostMode.shared_facet)\n",
    "mesh, subdomains, boundaries_and_interfaces = dolfinx.io.gmshio.model_to_mesh(\n",
    "    gmsh.model, comm=mpi4py.MPI.COMM_WORLD, rank=0, gdim=2, partitioner=partitioner)\n",
    "gmsh.finalize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3e765b1-d0fe-4216-b863-f0c8697cddbf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create connectivities required by the rest of the code\n",
    "mesh.topology.create_connectivity(mesh.topology.dim - 1, mesh.topology.dim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64ac1b0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "boundaries_1 = boundaries_and_interfaces.indices[boundaries_and_interfaces.values == 1]\n",
    "boundaries_2 = boundaries_and_interfaces.indices[boundaries_and_interfaces.values == 2]\n",
    "boundaries_3 = boundaries_and_interfaces.indices[boundaries_and_interfaces.values == 3]\n",
    "interfaces_4 = boundaries_and_interfaces.indices[boundaries_and_interfaces.values == 4]\n",
    "boundaries_12 = boundaries_and_interfaces.indices[np.isin(boundaries_and_interfaces.values, (1, 2))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0afcf8f0-6bf8-4be3-b547-f3ada64097bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "integration_entities_on_Gamma_obs = dolfinx.fem.compute_integration_domains(\n",
    "    dolfinx.fem.IntegralType.interior_facet, mesh.topology, interfaces_4)\n",
    "integration_entities_on_Gamma_obs_reshaped = integration_entities_on_Gamma_obs.reshape(-1, 4)\n",
    "connected_cells_to_Gamma_obs = integration_entities_on_Gamma_obs_reshaped[:, [0, 2]]\n",
    "subdomain_ordering = (\n",
    "    subdomains.values[connected_cells_to_Gamma_obs[:, 0]] < subdomains.values[connected_cells_to_Gamma_obs[:, 1]])\n",
    "if len(subdomain_ordering) > 0 and any(subdomain_ordering):\n",
    "    integration_entities_on_Gamma_obs_reshaped[subdomain_ordering] = integration_entities_on_Gamma_obs_reshaped[\n",
    "        subdomain_ordering][:, [2, 3, 0, 1]]\n",
    "integration_entities_on_Gamma_obs = integration_entities_on_Gamma_obs_reshaped.flatten()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22a3320a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define associated measures\n",
    "ds = ufl.Measure(\"ds\", subdomain_data=boundaries_and_interfaces)\n",
    "dS = ufl.Measure(\"dS\", domain=mesh, subdomain_data=[(4, np.array(integration_entities_on_Gamma_obs, dtype=np.int32))])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17cd4bc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Normal and tangent\n",
    "n = ufl.FacetNormal(mesh)\n",
    "t = ufl.as_vector([n[1], -n[0]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e3925c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_mesh(mesh)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a15af49c",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_mesh_tags(mesh, boundaries_and_interfaces, \"boundaries and interfaces\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5720e77",
   "metadata": {},
   "source": [
    "### Function spaces"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e76eba66",
   "metadata": {},
   "outputs": [],
   "source": [
    "Y_velocity = dolfinx.fem.functionspace(mesh, (\"Lagrange\", 2, (mesh.geometry.dim, )))\n",
    "Y_pressure = dolfinx.fem.functionspace(mesh, (\"Lagrange\", 1))\n",
    "U = dolfinx.fem.functionspace(mesh, (\"Lagrange\", 2, (mesh.geometry.dim, )))\n",
    "Q_velocity = Y_velocity.clone()\n",
    "Q_pressure = Y_pressure.clone()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aaad9d5d",
   "metadata": {},
   "source": [
    "### Restrictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "669bdf75",
   "metadata": {},
   "outputs": [],
   "source": [
    "dofs_Y_velocity = np.arange(0, Y_velocity.dofmap.index_map.size_local + Y_velocity.dofmap.index_map.num_ghosts)\n",
    "dofs_Y_pressure = np.arange(0, Y_pressure.dofmap.index_map.size_local + Y_pressure.dofmap.index_map.num_ghosts)\n",
    "dofs_U = dolfinx.fem.locate_dofs_topological(U, boundaries_and_interfaces.dim, boundaries_3)\n",
    "dofs_Q_velocity = dofs_Y_velocity\n",
    "dofs_Q_pressure = dofs_Y_pressure\n",
    "restriction_Y_velocity = multiphenicsx.fem.DofMapRestriction(Y_velocity.dofmap, dofs_Y_velocity)\n",
    "restriction_Y_pressure = multiphenicsx.fem.DofMapRestriction(Y_pressure.dofmap, dofs_Y_pressure)\n",
    "restriction_U = multiphenicsx.fem.DofMapRestriction(U.dofmap, dofs_U)\n",
    "restriction_Q_velocity = multiphenicsx.fem.DofMapRestriction(Q_velocity.dofmap, dofs_Q_velocity)\n",
    "restriction_Q_pressure = multiphenicsx.fem.DofMapRestriction(Q_pressure.dofmap, dofs_Q_pressure)\n",
    "restriction = [\n",
    "    restriction_Y_velocity, restriction_Y_pressure, restriction_U, restriction_Q_velocity, restriction_Q_pressure]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b25f6709",
   "metadata": {},
   "source": [
    "### Trial and test functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9532a726",
   "metadata": {},
   "outputs": [],
   "source": [
    "(v, p) = (ufl.TrialFunction(Y_velocity), ufl.TrialFunction(Y_pressure))\n",
    "(w, q) = (ufl.TestFunction(Y_velocity), ufl.TestFunction(Y_pressure))\n",
    "u = ufl.TrialFunction(U)\n",
    "r = ufl.TestFunction(U)\n",
    "(z, b) = (ufl.TrialFunction(Q_velocity), ufl.TrialFunction(Q_pressure))\n",
    "(s, d) = (ufl.TestFunction(Q_velocity), ufl.TestFunction(Q_pressure))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9536f72",
   "metadata": {},
   "source": [
    " ### Problem data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5ea604e",
   "metadata": {},
   "outputs": [],
   "source": [
    "nu = 0.04\n",
    "alpha_1 = 0.001\n",
    "alpha_2 = 0.1 * alpha_1\n",
    "x = ufl.SpatialCoordinate(mesh)\n",
    "c = 0.8\n",
    "v_d = ufl.as_vector((\n",
    "    (c * 10.0 * (x[1]**3 - x[1]**2 - x[1] + 1.0)) + ((1.0 - c) * 10.0 * (-x[1]**3 - x[1]**2 + x[1] + 1.0)),\n",
    "    0.0))\n",
    "ff = dolfinx.fem.Constant(mesh, tuple(petsc4py.PETSc.ScalarType(0) for _ in range(2)))\n",
    "\n",
    "\n",
    "def g_eval(x: np.typing.NDArray[np.float64]) -> np.typing.NDArray[  # type: ignore[no-any-unimported]\n",
    "        petsc4py.PETSc.ScalarType]:\n",
    "    \"\"\"Return the parabolic velocity profile at the inlet.\"\"\"\n",
    "    values = np.zeros((2, x.shape[1]))\n",
    "    values[0, :] = 10.0 * (x[1, :] + 1.0) * (1.0 - x[1, :])\n",
    "    return values\n",
    "\n",
    "\n",
    "g = dolfinx.fem.Function(Y_velocity)\n",
    "g.interpolate(g_eval)\n",
    "bc0 = dolfinx.fem.Function(Y_velocity)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "baa4af9b",
   "metadata": {},
   "source": [
    "### Optimality conditions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a979c9eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def tracking(v: ufl.Argument, w: ufl.Argument) -> ufl.core.expr.Expr:  # type: ignore[no-any-unimported]\n",
    "    \"\"\"Return the UFL expression corresponding to the tracking term.\"\"\"\n",
    "    return ufl.inner(v, w)(\"-\")\n",
    "\n",
    "\n",
    "def penalty(u: ufl.Argument, r: ufl.Argument) -> ufl.core.expr.Expr:  # type: ignore[no-any-unimported]\n",
    "    \"\"\"Return the UFL expression corresponding to the penalty term.\"\"\"\n",
    "    return alpha_1 * ufl.inner(ufl.grad(u) * t, ufl.grad(r) * t) + alpha_2 * ufl.inner(u, r)\n",
    "\n",
    "\n",
    "a = [[tracking(v, w) * dS(4), None, None, nu * ufl.inner(ufl.grad(z), ufl.grad(w)) * ufl.dx,\n",
    "      - ufl.inner(b, ufl.div(w)) * ufl.dx],\n",
    "     [None, None, None, - ufl.inner(ufl.div(z), q) * ufl.dx, None],\n",
    "     [None, None, penalty(u, r) * ds(3), - ufl.inner(z, r) * ds(3), None],\n",
    "     [nu * ufl.inner(ufl.grad(v), ufl.grad(s)) * ufl.dx, - ufl.inner(p, ufl.div(s)) * ufl.dx,\n",
    "      - ufl.inner(u, s) * ds(3), None, None],\n",
    "     [- ufl.inner(ufl.div(v), d) * ufl.dx, None, None, None, None]]\n",
    "f = [tracking(v_d, w) * dS(4),\n",
    "     None,\n",
    "     None,\n",
    "     ufl.inner(ff, s) * ufl.dx,\n",
    "     None]\n",
    "a[0][0] += dolfinx.fem.Constant(mesh, petsc4py.PETSc.ScalarType(0)) * ufl.inner(v, w) * (ds(1) + ds(2))\n",
    "a[3][3] = dolfinx.fem.Constant(mesh, petsc4py.PETSc.ScalarType(0)) * ufl.inner(z, s) * (ds(1) + ds(2))\n",
    "f[1] = ufl.inner(dolfinx.fem.Constant(mesh, petsc4py.PETSc.ScalarType(0)), q) * ufl.dx\n",
    "f[2] = ufl.inner(dolfinx.fem.Constant(mesh, tuple(petsc4py.PETSc.ScalarType(0) for _ in range(2))), r) * ufl.dx\n",
    "f[4] = ufl.inner(dolfinx.fem.Constant(mesh, petsc4py.PETSc.ScalarType(0)), d) * ufl.dx\n",
    "a_cpp = dolfinx.fem.form(a)\n",
    "f_cpp = dolfinx.fem.form(f)\n",
    "bdofs_Y_velocity_1 = dolfinx.fem.locate_dofs_topological(\n",
    "    (Y_velocity, Y_velocity), mesh.topology.dim - 1, boundaries_1)\n",
    "bdofs_Y_velocity_2 = dolfinx.fem.locate_dofs_topological(\n",
    "    (Y_velocity, Y_velocity), mesh.topology.dim - 1, boundaries_2)\n",
    "bdofs_Q_velocity_12 = dolfinx.fem.locate_dofs_topological(\n",
    "    (Q_velocity, Y_velocity), mesh.topology.dim - 1, boundaries_12)\n",
    "bc = [dolfinx.fem.dirichletbc(g, bdofs_Y_velocity_1, Y_velocity),\n",
    "      dolfinx.fem.dirichletbc(bc0, bdofs_Y_velocity_2, Y_velocity),\n",
    "      dolfinx.fem.dirichletbc(bc0, bdofs_Q_velocity_12, Q_velocity)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36e562f8",
   "metadata": {},
   "source": [
    "### Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c53752f",
   "metadata": {},
   "outputs": [],
   "source": [
    "(v, p) = (dolfinx.fem.Function(Y_velocity), dolfinx.fem.Function(Y_pressure))\n",
    "u = dolfinx.fem.Function(U)\n",
    "(z, b) = (dolfinx.fem.Function(Q_velocity), dolfinx.fem.Function(Q_pressure))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f97eb270",
   "metadata": {},
   "source": [
    "### Cost functional"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e366450",
   "metadata": {},
   "outputs": [],
   "source": [
    "J = 0.5 * tracking(v - v_d, v - v_d) * dS(4) + 0.5 * penalty(u, u) * ds(3)\n",
    "J_cpp = dolfinx.fem.form(J)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1db86aa3",
   "metadata": {},
   "source": [
    "### Uncontrolled functional value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70c20874",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Extract state forms from the optimality conditions\n",
    "a_state = [[ufl.replace(a[i][j], {s: w, d: q}) if a[i][j] is not None else None for j in (0, 1)] for i in (3, 4)]\n",
    "f_state = [ufl.replace(f[i], {s: w, d: q}) for i in (3, 4)]\n",
    "a_state_cpp = dolfinx.fem.form(a_state)\n",
    "f_state_cpp = dolfinx.fem.form(f_state)\n",
    "bc_state = [bc[0], bc[1]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee1d0f22",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Assemble the block linear system for the state\n",
    "A_state = multiphenicsx.fem.petsc.assemble_matrix_block(\n",
    "    a_state_cpp, bcs=bc_state, restriction=([restriction[i] for i in (3, 4)], [restriction[j] for j in (0, 1)]))\n",
    "A_state.assemble()\n",
    "F_state = multiphenicsx.fem.petsc.assemble_vector_block(\n",
    "    f_state_cpp, a_state_cpp, bcs=bc_state, restriction=[restriction[i] for i in (3, 4)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2d875d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solve\n",
    "vp = multiphenicsx.fem.petsc.create_vector_block(\n",
    "    [f_cpp[j] for j in (0, 1)], restriction=[restriction[j] for j in (0, 1)])\n",
    "ksp = petsc4py.PETSc.KSP()\n",
    "ksp.create(mesh.comm)\n",
    "ksp.setOperators(A_state)\n",
    "ksp.setType(\"preonly\")\n",
    "ksp.getPC().setType(\"lu\")\n",
    "ksp.getPC().setFactorSolverType(\"mumps\")\n",
    "ksp.setFromOptions()\n",
    "ksp.solve(F_state, vp)\n",
    "vp.ghostUpdate(addv=petsc4py.PETSc.InsertMode.INSERT, mode=petsc4py.PETSc.ScatterMode.FORWARD)\n",
    "ksp.destroy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "188a81a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split the block solution in components\n",
    "with multiphenicsx.fem.petsc.BlockVecSubVectorWrapper(\n",
    "        vp, [c.function_space.dofmap for c in (v, p)], [restriction[j] for j in (0, 1)]) as vp_wrapper:\n",
    "    for vp_wrapper_local, component in zip(vp_wrapper, (v, p)):\n",
    "        with component.x.petsc_vec.localForm() as component_local:\n",
    "            component_local[:] = vp_wrapper_local\n",
    "vp.destroy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49d5c1a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "J_uncontrolled = mesh.comm.allreduce(dolfinx.fem.assemble_scalar(J_cpp), op=mpi4py.MPI.SUM)\n",
    "print(\"Uncontrolled J =\", J_uncontrolled)\n",
    "assert np.isclose(J_uncontrolled, 2.8479865)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0959d5db",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_vector_field(v, \"uncontrolled state velocity\", glyph_factor=1e-2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "274fac42",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_scalar_field(p, \"uncontrolled state pressure\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b722f872",
   "metadata": {},
   "source": [
    "### Optimal control"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2024d451",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Assemble the block linear system for the optimality conditions\n",
    "A = multiphenicsx.fem.petsc.assemble_matrix_block(a_cpp, bcs=bc, restriction=(restriction, restriction))\n",
    "A.assemble()\n",
    "F = multiphenicsx.fem.petsc.assemble_vector_block(f_cpp, a_cpp, bcs=bc, restriction=restriction)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a63c207f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solve\n",
    "vpuzb = multiphenicsx.fem.petsc.create_vector_block(f_cpp, restriction=restriction)\n",
    "ksp = petsc4py.PETSc.KSP()\n",
    "ksp.create(mesh.comm)\n",
    "ksp.setOperators(A)\n",
    "ksp.setType(\"preonly\")\n",
    "ksp.getPC().setType(\"lu\")\n",
    "ksp.getPC().setFactorSolverType(\"mumps\")\n",
    "ksp.setFromOptions()\n",
    "ksp.solve(F, vpuzb)\n",
    "vpuzb.ghostUpdate(addv=petsc4py.PETSc.InsertMode.INSERT, mode=petsc4py.PETSc.ScatterMode.FORWARD)\n",
    "ksp.destroy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dee34729",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split the block solution in components\n",
    "with multiphenicsx.fem.petsc.BlockVecSubVectorWrapper(\n",
    "        vpuzb, [c.function_space.dofmap for c in (v, p, u, z, b)], restriction) as vpuzb_wrapper:\n",
    "    for vpuzb_wrapper_local, component in zip(vpuzb_wrapper, (v, p, u, z, b)):\n",
    "        with component.x.petsc_vec.localForm() as component_local:\n",
    "            component_local[:] = vpuzb_wrapper_local\n",
    "vpuzb.destroy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4023007",
   "metadata": {},
   "outputs": [],
   "source": [
    "J_controlled = mesh.comm.allreduce(dolfinx.fem.assemble_scalar(J_cpp), op=mpi4py.MPI.SUM)\n",
    "print(\"Optimal J =\", J_controlled)\n",
    "assert np.isclose(J_controlled, 1.7643950)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f880f43",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_vector_field(v, \"state velocity\", glyph_factor=1e-2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b15d28d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_scalar_field(p, \"state pressure\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7db5083d",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_vector_field(u, \"control\", glyph_factor=1e-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82db3b8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_vector_field(z, \"adjoint velocity\", glyph_factor=1e-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "217e02e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "viskex.dolfinx.plot_scalar_field(b, \"adjoint pressure\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython"
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
